import {
	storage
} from '@/utils/cache'
import Vue from 'vue'

const types = {
	prizeList: 'prizeList', // 商品列表
	formIdList: 'formIdList', // formId列表
	enterUrl: 'enterUrl', // 小程序的启动路径和参数
	tabCurrent2:'tabCurrent2', //第二个tabBar的头部滑块参数
}

const state = {
	[types.prizeList]: [],
	[types.formIdList]: [],
	[types.enterUrl]: '',
	[types.tabCurrent2]: 0,
}

const getters = {
	_prizeList(state) {
		return state[types.prizeList]
	},
	_formIdList(state) {
		return state[types.formIdList]
	},
	_enterUrl(state) {
		return state[types.enterUrl]
	},
	_tabCurrent2(state) {
		return state[types.tabCurrent2]
	},
}

const actions = {
	[types.prizeList + 'Load']: async ({
		commit
	}, state) => {
		const prizeList = await Vue.prototype.$api.home.productList({});
		return commit(types.prizeList, prizeList)
	},
	[types.enterUrl + 'Up']: async ({
		commit,
		state,
		dispatch
	}, e = {"query":{},"path":"pages/tabBar/home/index"}) => {
		//保存启动路径
		let str = []
		for (var p in e.query) {
			if (e.query.hasOwnProperty(p)) {
				str.push(encodeURIComponent(p) + '=' + encodeURIComponent(e.query[p]))
			}
		}
		const query = str.join('&')
		const enterUrl = '/' + e.path + (query ? '?' + query : '')
		console.log(enterUrl)
		return commit(types.enterUrl, enterUrl)
	},
	[types.tabCurrent2 + 'Up']: async ({
		commit,
		state,
		dispatch
	}, current=0) => {
		return commit(types.tabCurrent2, current)
	},
	[types.formIdList + 'Up']: async ({
		commit,
		dispatch,
		state
	}, {
		e,
		isSave
	} = {}) => {
		console.error(e.detail.formId)
		const formId = e.detail.formId;
		const formIdList = state.formIdList
		if (formId && formId != 'the formId is a mock one') {
			const createTime = new Date().getTime()
			formIdList.push({
				formId,
				createTime
			})
		}
		commit(types.formIdList, formIdList)
		if (isSave) {
			dispatch('saveFormId');
		}
		return
	},
	saveFormId: async ({
		commit,
		state
	}, {} = {}) => {
		const formIdList = state.formIdList
		console.log(formIdList)
		if (!formIdList || formIdList.length == 0) return
		try {
			await Vue.prototype.$api.home.saveFormId({
				formIdAoList: formIdList
			});
			console.error('api.saveFormId')
		} catch (e) {
			console.error(e)
			uni.setStorageSync(types.formIdList, formIdList)
		}
		return commit(types.formIdList, [])
	},
	initFormIdList: async ({
		commit,
		state
	}, {} = {}) => {
		return
		const formIdList = await uni.getStorageSync(types.formIdList) || [];
		commit(types.formIdList, formIdList)
		return uni.removeStorageSync(types.formIdList)
	},
}

const mutations = {
	[types.prizeList]: (state, res) => {
		state[types.prizeList] = res
	},
	[types.formIdList]: (state, res) => {
		state[types.formIdList] = res
	},
	[types.enterUrl]: (state, res) => {
		state[types.enterUrl] = res
	},
	[types.tabCurrent2]: (state, res) => {
		state[types.tabCurrent2] = res
	},
}

export default {
	namespaced: true,
	types,
	state,
	getters,
	actions,
	mutations
}
